/**
 * Created by ezgoing on 14/9/2014.
 */

(function ($) {
    var cropbox = function(options, el){
        var el = el || $(options.imageBox),
            obj =
            {                
                x1:null,
                x2:null,
                y1:null,
                y2:null,
                baseScale:1,
                state : {},
                ratio : 1,
                options : options,
                imageBox : el,
                thumbBox : el.find(options.thumbBox),
                spinner : el.find(options.spinner),
                image : new Image(),
                getDataURL: function ()
                {
                    var width = this.thumbBox.width(),
                        height = this.thumbBox.height(),
                        canvas = document.createElement("canvas"),
                        dim = el.css('background-position').split(' '),
                        size = el.css('background-size').split(' '),
                        dx = parseInt(dim[0]) - el.width()/2 + width/2,
                        dy = parseInt(dim[1]) - el.height()/2 + height/2,
                        dw = parseInt(size[0]),
                        dh = parseInt(size[1]),
                        sh = parseInt(this.image.height),
                        sw = parseInt(this.image.width);

                    canvas.width = width;
                    canvas.height = height;
                    var context = canvas.getContext("2d");
                    context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh);
                    var imageData = canvas.toDataURL('image/png');
                    return imageData;
                },
                getBlob: function()
                {
                    var imageData = this.getDataURL();
                    var b64 = imageData.replace('data:image/png;base64,','');
                    var binary = atob(b64);
                    var array = [];
                    for (var i = 0; i < binary.length; i++) {
                        array.push(binary.charCodeAt(i));
                    }
                    return  new Blob([new Uint8Array(array)], {type: 'image/png'});
                },
                zoomIn: function ()
                {
                    this.ratio *= 1.1;
                    
                    setBackground();
                },
                zoomOut: function ()
                {
                    this.ratio*=0.9;
                    if(this.ratio<this.baseScale){
                        this.ratio=this.baseScale;
                    }
                    setBackground();
                }
            },
            setBackground = function()
            {
                window.bgW =  parseInt(obj.image.width) * obj.ratio;
                window.bgH =  parseInt(obj.image.height) * obj.ratio;

                var pw = (el.width() - window.bgW) / 2;
                var ph = (el.height() - window.bgH) / 2;
                el.css({
                    'background-image': 'url(' + obj.image.src + ')',
                    'background-size': window.bgW +'px ' + window.bgH + 'px',
                    'background-position': pw + 'px ' + ph + 'px',
                    'background-repeat': 'no-repeat'});
            },
            imgMouseDown = function(e)
            {
                e.preventDefault();
                e.stopPropagation();
               //e.stopImmediatePropagation();

                if (e.originalEvent.touches.length == 1) {
                    var tmpE = e.originalEvent.touches[0];
                    obj.state.dragable = true;
                    obj.state.mouseX = tmpE.clientX;
                    obj.state.mouseY = tmpE.clientY;
                }
            },
            imgMouseMove = function(e)
            {
                e.preventDefault();
                e.stopPropagation();
                if (e.originalEvent.touches.length == 1){
                    var tmpE = getEvent(e);
                    if (obj.state.dragable)
                    {
                        var x = tmpE.clientX - obj.state.mouseX;
                        var y = tmpE.clientY - obj.state.mouseY;

                        var bg = el.css('background-position').split(' ');

                        var bgX = x + parseInt(bg[0]);
                        var bgY = y + parseInt(bg[1]);

                        if(bgX > obj.x1 ){
                            bgX = obj.x1;
                        }else if(bgX < (obj.x2 -window.bgW)){
                            bgX=obj.x2 -window.bgW;
                        }
                        if(bgY > obj.y1){
                            bgY = obj.y1;
                        }else if(bgY < (obj.y2-window.bgH) ){
                            bgY = obj.y2-window.bgH;
                        }

                        el.css('background-position', bgX +'px ' + bgY + 'px');
                        obj.state.mouseX = tmpE.clientX;
                        obj.state.mouseY = tmpE.clientY;
                    }

                }
            },
            getEvent=function(event) {
                switch (event.type) {
                    case 'touchstart':
                    case 'touchmove':
                    case 'touchend':
                    case 'touchcancel':
                        return event.originalEvent.touches[0];
                    default:
                        return event;
                }
            },
            imgMouseUp = function(e)
            {
                e.preventDefault();
                e.stopPropagation();
                //e.stopImmediatePropagation();
                obj.state.dragable = false;
            },
            zoomImage = function(e)            {
                e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0 ? obj.ratio*=1.1 : obj.ratio*=0.9;
                if(obj.ratio<obj.baseScale){
                    obj.ratio=obj.baseScale;
                }
                setBackground();
            }

        obj.spinner.show();
        obj.image.onload = function() {
            obj.spinner.hide();
            obj.baseScale=Math.max($('.imageBox').width() / obj.image.width , $('.imageBox').height() / obj.image.height);
            obj.ratio=obj.baseScale;
            setBackground();
            obj.x1 = obj.thumbBox.offset().left - el.offset().left;
            obj.x2 = obj.thumbBox.offset().left + el.offset().left + obj.thumbBox.width();
            obj.y1 = obj.thumbBox.offset().top - el.offset().top;
            obj.y2 = obj.thumbBox.offset().top - el.offset().top + obj.thumbBox.height();

            el.bind('touchstart mousedown', imgMouseDown);
            el.bind('touchmove mousemove', imgMouseMove);
            el.bind('touchend mouseup', imgMouseUp);
            el.bind('mousewheel DOMMouseScroll', zoomImage);
        };
        obj.image.src = options.imgSrc;
        el.on('remove', function(){
            el.unbind('touchstart mousedown', imgMouseDown);
            el.unbind('touchmove mousemove', imgMouseMove);
            el.unbind('touchend mouseup', imgMouseUp);
            el.unbind('mousewheel DOMMouseScroll', zoomImage);

        });
        return obj;
    };
    jQuery.fn.cropbox = function(options){
        return new cropbox(options, this);
    };
})(jQuery);


